import { BASE_URL_TEST, BASE_URL_PROD } from "@/config";
import request from "./request";
import { Token } from "@/utils/cache";

const baseUrl =
  import.meta.env.MODE !== "development" ? BASE_URL_PROD : BASE_URL_TEST;
/**
 * @params
 * @returns 获取用户基本信息
 */
export function GetUserInfoApi() {
  return request({ url: "/user" });
}

/**
 * @params data
 * @returns 修改用户信息
 */
export async function UpdateUserInfoApi(data: any) {
  // #ifndef H5
  console.log("data", data);
  return new Promise((resolve, reject) => {
    function uploadFile(temp: string) {
      uni.uploadFile({
        url: baseUrl + "/user",
        filePath: temp,
        name: "profile_photo",
        header: {
          token: Token.get()
        },
        formData: {
          gender: data.gender,
          info: data.info,
          user_name: data.user_name
        },
        success(res: any) {
          console.log("success", res);
          resolve(JSON.parse(res.data));
        },
        fail(error: any) {
          console.log("error", error);
          reject(null);
        }
      });
    }
    if (typeof data.profile_photo === "string") {
      uni.downloadFile({
        url: data.profile_photo,
        success(res: any) {
          uploadFile(res.tempFilePath);
        }
      });
      return;
    }
    uploadFile(data.profile_photo.path);
  });
  // #endif
  // #ifdef H5
  delete data.address;
  const formData = new FormData();
  for (const k in data) {
    if (data[k]) {
      formData.append(k, data[k]);
    }
  }
  const response = await fetch(baseUrl + "/user", {
    method: "POST",
    headers: {
      token: Token.get()
    },
    body: formData
  });
  return response.json();
  // #endif
}

/**
 * @params
 * @returns 退出登录
 */
export function LogoutApi() {
  return request({ url: "/user/login-out", method: "POST" });
}

export function orderList() {
  return request({ url: "/order/list", data: { page: 1, per_page: 100 } });
}

export function advice(question: string, desc: string) {
  return request({ url: "/advice", method: "POST", data: { question, desc } });
}
// 帮助中心
export function helperList() {
  return request({ url: "/helper/list" });
}
//隐私
export function privacyNotes(type: string) {
  return request({ url: "/user-notes", data: { type } });
}

export function homepage() {
  return request({ url: "/homepage" });
}

export function articleDetail(news_id: string) {
  return request({ url: "/news", isToken: false, data: { news_id } });
}
